#!/usr/bin/env python
import itertools
import cherrypy
import os
import threading
import random
import time
import fileinput
import  json

class OneMarkov(object):
    def __init__(self):
        self.dic1={}
        self.average=0
        self.count=0
        self.no_request=0
        self.no_of_request=0
        self.n=0

    def try12(self):
        dic2={}
        n=0
        for line in fileinput.input(['D:\\Data\\3days\\train_d.csv']):
                try:
                        self.train(line,n,self.dic1)
                except:
                    continue
    def test12(self,line):
        self.n+=1
        self.average,self.count,self.no_of_request,self.no_request=self.test(line,self.n,self.average,self.count,self.dic1,self. no_of_request,self.no_request)
        coverage=float(self.no_of_request-self.no_request)/float(self.no_of_request)*100
        return self.average*100,coverage
         
        
                    
    def train(self,line, n,dic1): # this is a training method 
        count1=0
        print "INSIDE TRAIN"
        line2= line.strip().rstrip(',')
        line1=line2.split(',') # to get the elements/domain number in a sessions
        length=len(line1)-1
        for i in range(0,length):
            j=i+1
            if dic1.has_key(line1[i]):
                value=dic1.get(line1[i])
                count1=value[0]
                dic2=value[1]
                count1=int(count1)+1
                if dic2.has_key(line1[j]):
                    dic2[line1[j]]=int(dic2.get(line1[j]))+1
                else:
                    dic2[line1[j]]=1
                    dic1[line1[i]]=(count1,dic2)
            else:
                count2=1
                dic3={}
                dic3[line1[j]]=1
                dic1[line1[i]]=(count2,dic3)
    
        
    def test(self,line4,n,average,count,dic1,no_of_request,no_request):
        print "INSIDE TEST"
        list2=[]
        line5= line4.strip().rstrip(',')
        line6=line5.split(',')
        length=len(line6)-1
        for i in range(0,length):
            no_of_request+=1
            list2=self.recommend(line6[i],self.dic1)
            len1=len(list2)
            if len1==0:
                no_request+=1
            if not len1==0:
                count+=1
                j=i+1
                re=self.evaluate(list2,line6[j],count,average)   
                average=re[0]   
        self.train(line4,n,self.dic1)   
        print "Average:", average
        print "cov:",float(no_of_request-no_request)/float(no_of_request)
        return average,count,no_of_request,no_request
    
    
    def recommend(self,d1,dic1):
        list1 =[]
        value=dic1.get(d1)
        if (value==None):
            return list1
        print "*********"
        hash= value[1]
        list1=sorted(hash.iteritems(), key=lambda (k,v): (v,k))
        list1.reverse()
        len1=len(list1)
        resultlist=[]
        for u in range(0,len1):
            resultlist.append((list1[u])[0])
        return resultlist[0:20]
    
    
    def evaluate(self,recommendationlist,actual,count,average):
        correct=0
        print "aactural", actual
        print "rec", recommendationlist
        if actual in recommendationlist:
            average = self.calculateAccuracy(1,average,count)
            return (average,count,correct)
        else:
            average=self.calculateAccuracy(0,average,count)
            return (average,count,correct)
        
    def calculateAccuracy(self,correct,average,count):

            return ((int(count)-1)*float(average)+int(correct))/int(count)
        
        
        
        
class HelloWorld(object):
    def __init__(self):
        self.thread1 = myThread()
        self.thread1.start()
    def myjson(self):
        return "{\"value\":"+self.thread1.getAccuracy()+"}"
    def myjson2(self):
        return "{\"value\":"+self.thread1.getCoverage()+"}"
    def myjson3(self):
        return "{\"value\":"+self.thread1.getLine()+"}"
                     
    myjson.exposed = True
    myjson2.exposed = True
    myjson3.exposed = True

class myThread (threading.Thread):
    def __init__(self):
        self.accuracy = 0
        self.coverage=0
        self.line=[1,2]
        threading.Thread.__init__(self)
        
    def run(self):
        om= OneMarkov()
        om.try12()
#        while self.counter>-1:
        time.sleep(0.1)
        for line in fileinput.input(['D:\\Data\\3days\\test_d.csv']):
                try:
                    time.sleep(0.1)
                    self.line=line
                    self.accuracy=om.test12(line)[0]
                    self.coverage=om.test12(line)[1]
                except:
                    continue
            
#            self.counter+=random.randint(-5,5)     
#            if self.counter > 60 :
#                self.counter = 60
#            if self.counter < 0 :
#                self.counter = 0
    def getAccuracy(self):
        return str(self.accuracy)
    def getCoverage(self):
        return str(self.coverage)
    def getLine(self):
        return json.dumps(self.line)
        
        
PATH = os.path.abspath(os.path.dirname("D:\\Server\\"))
class Root(object): pass

#thread1 = myThread()
#thread1.start()
cherrypy.tree.mount(Root(), '/', config={
        '/': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': PATH,
                'tools.staticdir.index': 'index.html',
            },
    })

cherrypy.tree.mount(HelloWorld(),'/ajax')
cherrypy.engine.start()
cherrypy.engine.block()



#cherrypy.quickstart(HelloWorld())